package me.aartikov.alligator.converters;

import java.io.Serializable;

import me.aartikov.alligator.Screen;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.app.Context;
import ohos.utils.Sequenceable;


/**
 * Creates an intent that starts an activity of the given class. It also puts a screen to the intent's extra if {@code ScreenT} is {@code Serializable} or {@code Parcelable}.
 *
 * @param <ScreenT> screen type
 */
public class DefaultIntentConverter<ScreenT extends Screen> implements IntentConverter<ScreenT> {
    private static final String KEY_SCREEN = "me.aartikov.alligator.KEY_SCREEN";

    private Class<ScreenT> mScreenClass;
    private Class<? extends Ability> mActivityClass;

    public DefaultIntentConverter(Class<ScreenT> screenClass, Class<? extends Ability> activityClass) {
        mScreenClass = screenClass;
        mActivityClass = activityClass;
    }

    @Override
    public Intent createIntent(Context context, ScreenT screen) {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder().withBundleName(context.getBundleName()).withAbilityName(mActivityClass.getName()).build();
        intent.setOperation(operation);
        intent.setParams(new IntentParams());
        intent.getParams().setParam(KEY_SCREEN, (Serializable) screen);
        return intent;
    }

    @SuppressWarnings("unchecked")
    @Override

    public ScreenT getScreen(Intent intent) {
        if (Serializable.class.isAssignableFrom(mScreenClass)) {
            Object o = intent.getParams();
            if (o != null) {
                return (ScreenT) intent.getParams().getParam(KEY_SCREEN);
            }
            return null;
        } else if (Sequenceable.class.isAssignableFrom(mScreenClass)) {
            Object o = intent.getParams();
            if (o != null) {
                return (ScreenT) intent.getParams().getParam(KEY_SCREEN);
            }
            return null;
        } else {
            throw new IllegalArgumentException("Screen " + mScreenClass.getSimpleName() + " should be Serializable or Parcelable.");
        }
    }
}